﻿
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;


namespace BoilenEditor.Primitives {

    [DebuggerDisplay( "OpenData: SolutionDirectory={SolutionDirectory}" )]
    public partial class OpenData {

        public static OpenData Create( string projectDirectoryFilter ) {
            string solutionDirectory =
                Ex.Enumerate( Environment.CurrentDirectory, dir => !string.IsNullOrEmpty( dir ), Path.GetDirectoryName )
                  .FirstOrDefault( dir => Ex.TestFile( dir, "*.sln" ) )
                  ?? Environment.CurrentDirectory;

            return new OpenData { ProjectDirectoryFilter = projectDirectoryFilter, SolutionDirectory = solutionDirectory };
        }


        private void UpdateProjects( ) {
            this.Projects.Clear( );
            if( !this.SolutionDirectory.HasValue( ) )
                return;

            var projects =
                from path in Ex.GetFiles( this.SolutionDirectory, "*.csproj", this.ProjectDirectoryFilter )
                orderby path
                group path by Path.GetDirectoryName( path )
                    into g
                    let project = new ProjectData( g.First( ), this.SolutionDirectory, null )
                    where IncludeEmptyProjects || project.TemplateFiles.Any( )
                    select project;
            this.Projects.AddRange( projects );
        }

        partial void SolutionPathChanged( string oldValue ) {
            this.SolutionDirectory = Path.GetDirectoryName( this.SolutionPath );
        }

        partial void SolutionDirectoryChanged( string oldValue ) {
            UpdateProjects( );
        }

        partial void ProjectDirectoryFilterChanged( string oldValue ) {
            UpdateProjects( );
        }

        partial void IncludeEmptyProjectsChanged( bool oldValue ) {
            UpdateProjects( );
        }

    }

}
